package com.wenjh.jdmzt.service.dao;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;

import com.wenjh.jdmzt.service.model.Image;
import com.wenjh.jdmzt.util.Log4Android;

public class DBOpenHandler extends SQLiteOpenHelper {
	private final static int DB_MIN_VERSION = 8;
	private final static int DB_VERSION = DB_MIN_VERSION;

	private String name = null;
	private Log4Android log = new Log4Android(this);

	/**
	 * 构建一个数据库操作对象
	 * 
	 * @param context
	 * @param dbpath
	 *            数据库位置，不能为空。并且，其父目录结构必须已经存在
	 */
	public DBOpenHandler(Context context) {
		super(context, "photos", null, DB_VERSION);
	}
	
	public String getName() {
		return name;
	}
	
	public void onCreate(SQLiteDatabase db) {
		String createTableSql = null;
		// 图片表
		createTableSql = "CREATE TABLE IF NOT EXISTS "
				+ Image.Table.TableName + "(" + 
				Image.Table.DBFIELD_ID + " INTEGER primary key autoincrement,";
		db.execSQL(addTmpField(createTableSql, 20));
		
		// 用户表
		/*createTableSql = "CREATE TABLE IF NOT EXISTS "
				+ User.Table.TableName + "(" + 
				User.Table.F_ID + " VARCHAR(50) primary key,";
		db.execSQL(addTmpField(createTableSql, 50));*/
	}

	private String addTmpField(String sql) {
		return addTmpField(sql, 20);
	}

	private String addTmpField(String sql, int filedCount) {
		for (int i = 1; i < filedCount; i++) {
			String field = ITable.DBFILED_TMP + i + " NUMERIC";
			if (i < filedCount - 1) {
				field += ",";
			}

			sql += field;
		}

		sql += ")";

		return sql;
	}


	@Override
	public void onUpgrade(final SQLiteDatabase db, final int oldVersion,
			final int newVersion) {
		this.onCreate(db);
	}
	
	@Override
	public void onOpen(SQLiteDatabase db) {
		super.onOpen(db);
	}
}
